package cj.web.admin.controllers;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.web.admin.dao.VoteDAO;
import cj.web.admin.dao.VoteItemDAO;
import cj.web.admin.dao.VoteSubjectDAO;
import cj.web.admin.domain.Vote;
import cj.web.admin.domain.VoteItem;
import cj.web.admin.domain.VoteSubject;
import cj.web.constants.MemuEnum;
import cj.web.constants.isLoginEnum;
import cj.web.constants.isMutilEnum;
import cj.web.login.controllers.BaseController;

@Path("/voteC")
public class VoteCribbingController extends BaseController{

	private static Logger logger = Logger.getLogger(VoteCribbingController.class.getName());
	
	@Autowired
	private VoteDAO voteDao;
	
	@Autowired
	private VoteItemDAO voteItemDao;
	
	@Autowired
	private VoteSubjectDAO voteSubjectDao;
	
	@Get("show")
	public String show(Model model, HttpServletRequest request) {
	
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgxgtps);
        model.add("isLoginEnum",EnumSet.allOf(isLoginEnum.class));
		return "/views/vote/voteCribbingList.vm";
	}

	@Post("getList")
	public String queryList(Vote vote) {
	
		List<Vote> arr = voteDao.query(vote);
		
		for(Vote obj:arr)
		{
			obj.setVoteStart(DateUtils.getMinusTime(obj.getVoteStart(), DateUtils.DATE_FULL_STR, 0));
			obj.setVoteEnd(DateUtils.getMinusTime(obj.getVoteEnd(), DateUtils.DATE_FULL_STR, 0));
		}
		
		JSONObject jo = new JSONObject();
		
		int size = voteDao.querysize(vote);
		
		jo.put("data", arr);
		jo.put("draw", vote.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	//--------VoteSubject--------
	@Get("showSj")
	public String showSubject(Model model,@Param("id") int id, HttpServletRequest request) {
		Vote vote =voteDao.queryById(id);
		//MemuEnum
		model.add("voteId",id);
		model.add("vote",vote);
        model.add("MemuEnum",MemuEnum.lkgxgtps);
        model.add("isMutilEnum",EnumSet.allOf(isMutilEnum.class));
		return "/views/vote/voteCribbingSubjectList.vm";
	}

	@Post("getSjList")
	public String querySubjectList(VoteSubject voteSubject) {
	
		List<Map> arr = voteSubjectDao.query(voteSubject);
		
		for(Map subject : arr){
			int subjectId = Integer.parseInt(subject.get("id").toString());
			List<Map> itms = voteItemDao.queryBySubjectId(subjectId);
			int total = 0;
			if(itms != null && itms.size() > 0){
				for(Map itm : itms){
					int count = Integer.parseInt(itm.get("count").toString());
					total += count;
				}
			}
			
			subject.put("total", total);
		}
		
		JSONObject jo = new JSONObject();
		
		int size = voteSubjectDao.querysize(voteSubject);
		
		jo.put("data", arr);
		jo.put("draw", voteSubject.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	//--------VoteItem--------
	@Get("showItem")
	public String showItem(Model model,@Param("id") int id,@Param("voteId") int voteId, HttpServletRequest request) {
	
		VoteSubject voteSubject =voteSubjectDao.queryById(id);
		//MemuEnum
		model.add("subjectId",id);
		model.add("voteId",voteId);
		model.add("voteSubject",voteSubject);
        model.add("MemuEnum",MemuEnum.lkgxgtps);
		return "/views/vote/voteCribbingItemList.vm";
	}

	@Post("getItemList")
	public String queryItemList(VoteItem voteItem) {
	
		List<Map> items = voteItemDao.query(voteItem);
		
		int total = 0;
		if(null != items && items.size() > 0){
			for(Map item : items){
				int count = Integer.parseInt(item.get("count").toString());
				total += count;
			}
			
			if(total == 0){
				for(Map item : items){
					item.put("percent", "0%");
				}
			}
			else{
//				int headPercents = 0;
				
				for(int i = 0; i < items.size(); i++){
					int count = Integer.parseInt(items.get(i).get("count").toString());
					if( count == 0 ){
						items.get(i).put("percent", "0%");
					}
					else{
//						int percent = Math.round((float)count/total * 100);
//						if( i ==  items.size() -1 && headPercents <= 100){
//							percent = 100 - headPercents;
//						}
//						headPercents += percent;
						String percent = accuracy(count, total, 2);
						items.get(i).put("percent", percent + "%");
					}
					
				}
			}
		}
		
		JSONObject jo = new JSONObject();
		
		int size = voteItemDao.querysize(voteItem);
		
		jo.put("data", items);
		jo.put("draw", voteItem.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("editItem")
	public String editItem(Model model,@Param("id") int id){
		
		VoteItem voteItem =voteItemDao.queryById(id);
		
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgxgtps);
        model.add("obj",voteItem);
		return "/views/vote/voteCribbingItemEdit.vm";
	}
	
	@Post("updateItem")
	public String updateItem(Model model,VoteItem voteItem,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			voteItem.setUpdateUser(returnSessionObj(request).getAccount());
			voteItemDao.updateCount(voteItem.getId(),voteItem.getCount());
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	private String accuracy(double num, double total, int scale) {
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		// 可以设置精确几位小数
		df.setMaximumFractionDigits(scale);
		// 模式 例如四舍五入
		df.setRoundingMode(RoundingMode.HALF_UP);
		double accuracy_num = num / total * 100;
		return df.format(accuracy_num);
	}
}